package cn.sylinx.horm.spring.scan;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import cn.sylinx.horm.proxy.command.annotation.Command;
import cn.sylinx.horm.util.GLog;

public class CommandScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

	private ResourceLoader resourceLoader;
	private List<String> packages;

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		
		GLog.info("Starting CommandScannerRegistrar at:{}", new Date());
		
		GLog.debug("Searching for command annotated with @Command");
		ClassPathCommandScanner scanner = new ClassPathCommandScanner(registry);
		try {
			if (this.resourceLoader != null) {
				scanner.setResourceLoader(this.resourceLoader);
			}
			scanner.setAnnotationClass(Command.class);
			scanner.registerFilters();
			scanner.doScan(StringUtils.toStringArray(getPackages()));
		} catch (IllegalStateException ex) {
			GLog.debug("Could not determine auto-configuration package, automatic command scanning disabled.", ex);
		}
	}

	public List<String> getPackages() {
		return packages;
	}

	public void setPackages(List<String> packages) {
		this.packages = packages;
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}
}